import React from 'react';
import { Upload } from 'antd';
import { UploadProps } from 'antd/lib/upload/interface';
import fileUpload from './file-upload';

import 'antd/lib/upload/style';

export interface FileChunkUploadProps
  extends Omit<UploadProps, 'customRequest'> {
  urlStartFiles: string;
  urlUploadChunk: string;
  urlAssembleFile: string;
}

const FileChunkUpload: React.FC<FileChunkUploadProps> = ({
  children,
  urlStartFiles,
  urlUploadChunk,
  urlAssembleFile,
  ...outerProps
}) => {
  const props: UploadProps = {
    ...outerProps,
    customRequest: options => {
      const { file } = options;
      const { onError, onProgress, onSuccess } = options;
      fileUpload({
        file,
        urlStartFiles,
        urlUploadChunk,
        urlAssembleFile,
        fileReadProgress: percent =>
          onProgress({ percent: percent * 0.3 }, file),
        chunkUploadProgress: percent =>
          onProgress({ percent: 30 + percent * 0.7 }, file),
        chunkUploadError: error => onError(error),
        fileUploadError: error => onError(error),
        fileUploadDone: data => onSuccess(data, file),
      });
    },
  };
  return <Upload {...props}>{children}</Upload>;
};

export default FileChunkUpload;
